'use strict';

module.exports = {

    async getDateXAxis(month){
        var moment = require('moment');
        let end = moment(month, "YYYY-MM").daysInMonth() // 31
        const {app,ctx,service} = this;
        let filters = {
            tab:0,
            startTime:month + '-01',
            endTime:month + '-' + end
        }
        var tab = filters.tab;
        var startTime = new Date(filters.startTime);
        var endTime = new Date(filters.endTime);
        var length = 0;   //日期跨度变量

        if( 0 == tab ) {
            length = (endTime.getTime() - startTime.getTime()) / (1000*24*60*60) + 1;
        } else if( 1 == tab ) {
            length = (endTime.getFullYear() - startTime.getFullYear()) * 12 + (endTime.getMonth() - startTime.getMonth()) + 1;
        } else {
            length = endTime.getFullYear() - startTime.getFullYear() + 1;
        }

        var xAxis = new Array(length);
        // xAxis[0] = filters.startTime;
        xAxis[0] = '01';
        for( var i = 1; i < length; i++ ) {
            if( 0 == tab ) {
                startTime.setDate( startTime.getDate() + 1 );
                xAxis[i] = startTime.Format("dd");
            } else if( 1 == tab ) {
                startTime.setMonth( startTime.getMonth() + 1 );
                xAxis[i] = startTime.Format("yyyy-MM");
            } else {
                startTime.setFullYear( startTime.getFullYear() + 1 );
                xAxis[i] = startTime.Format("yyyy");
            }
        }
        return xAxis;
    },

    /**
     * rabbitmq队列 入队
     * @param queueName
     * @param msg
     * @param errCallBack
     * @returns {Promise<void>}
     */
    async sendQueueMsg(queueName,msg){
        const {app,service,ctx} = this;
        var amqp = require('amqplib');

        //连接rabbitmq客户端
        amqp.connect('amqp://localhost').then(function(conn) {
            return conn.createChannel().then(function(ch) {
                var q = queueName;
                var ok = ch.assertQueue(q, {durable: true});
                return ok.then(function(_qok) {
                    // NB: `sentToQueue` and `publish` both return a boolean
                    // indicating whether it's OK to send again straight away, or
                    // (when `false`) that you should wait for the event `'drain'`
                    // to fire before writing again. We're just doing the one write,
                    // so we'll ignore it.
                    msg = JSON.stringify(msg)
                    ch.sendToQueue(q, Buffer.from(msg));
                    console.log(" [x] Sent '%s'", msg);
                    return ch.close();
                });
            }).finally(function() { conn.close(); });
        }).catch(console.warn);

        // const co = require('co');
        // const amqp = require('amqplib');
        //
        // co(function* () {
        //     // connection errors are handled in the co .catch handler
        //     const conn = yield amqp.connect('amqp://localhost');
        //
        //     // try catch will throw any errors from the yielding the following promises to the co .catch handler
        //     try {
        //         const q = 'hello';
        //         const msg = 'Hello World!';
        //
        //         // use a confirm channel so we can check the message is sent OK.
        //         const channel = yield conn.createConfirmChannel();
        //
        //         yield channel.assertQueue(q);
        //
        //         channel.sendToQueue(q, Buffer.from(msg));
        //
        //         // if message has been nacked, this will result in an error (rejected promise);
        //         yield channel.waitForConfirms();
        //
        //         console.log(" [x] Sent '%s'", msg);
        //
        //         channel.close();
        //     }
        //     catch (e) {
        //         throw e;
        //     }
        //     finally {
        //         conn.close();
        //     }
        //
        // }).catch(err => {
        //     console.warn('Error:', err);
        // });
    },

    /**
     * 充值队列
     * @returns {Promise<void>}
     */
    async receiveQueueMsg(){
        const {app,service,ctx} = this;
        var amqp = require('amqplib');
        amqp.connect('amqp://localhost').then(function(conn) {
            process.once('SIGINT', function() { conn.close(); });
            return conn.createChannel().then(function(ch) {

                var ok = ch.assertQueue('recharge', {durable: true});

                ok = ok.then(function(_qok) {
                    return ch.consume('recharge', async function(msg) {
                        console.log(" [x] Received '%s'", msg.content.toString());
                        msg = JSON.parse(msg.content.toString());
                        await service.rechargeService.recharge(msg.username,msg.money);
                    }, {noAck: true});
                });

                return ok.then(function(_consumeOk) {
                    console.log(' [*] Waiting for messages. To exit press CTRL+C');
                });
            });
        }).catch(console.warn);
    },

    /**
     * 抢单队列
     * @returns {Promise<void>}
     */
    async receiveQueueMsgStaff(){
        const {app,service,ctx} = this;
        var amqp = require('amqplib');
        amqp.connect('amqp://localhost').then(function(conn) {
            process.once('SIGINT', function() { conn.close(); });
            return conn.createChannel().then(function(ch) {

                var ok = ch.assertQueue('staff', {durable: true});

                ok = ok.then(function(_qok) {
                    return ch.consume('recharge', async function(msg) {
                        console.log(" [x] Received '%s'", msg.content.toString());
                        msg = JSON.parse(msg.content.toString());
                        await service.rabbitmq.change(msg.id,msg.param);
                    }, {noAck: true});
                });

                return ok.then(function(_consumeOk) {
                    console.log(' [*] Waiting for messages. To exit press CTRL+C');
                });
            });
        }).catch(console.warn);
    },

};
